package com.itita.ww2.handler.eventhandler;

import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.game.alliance.AllianceManager;
import com.itita.ww2.game.alliance.AllianceService;
import com.itita.ww2.game.cityconstruction.CityConstructionService;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.UserUtil;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

public class OnUserJoinZoneHandler extends BaseServerEventHandler {

	@Override
	public void handleServerEvent(ISFSEvent arg0) throws SFSException {
		User user = (User) arg0.getParameter(SFSEventParam.USER);
		if (UserUtil.isGuest(user)) {
			return;
		}
		UserProfile m_Profile = UserProfile.handleLogin(user); // 用户配置信息
		UserService.getInstance().handleUserJoin(m_Profile); // 更新(加入)缓存列表
		AllianceManager.getInstance().addAllianceUser(m_Profile); // 联盟缓存中加入新玩家
		// 初始化发个消息
		MessageHandler.getInstance().sendMsg("push.init", getUserInfo(m_Profile), user, null, true);
	}

	private final ISFSObject getUserInfo(UserProfile userProfile) {
		ISFSObject ref = SFSObject.newInstance();
		// 用户数据  
		// mapdata 在每次进入基地时再取
		ISFSObject userObj = SFSObject.newInstance();
		{
			userObj.putUtfString("nickname", userProfile.getNickname());
			userObj.putInt("channel", userProfile.getChannel());
			userObj.putSFSObject("info", userProfile.getUserInfo().toSFSObject());
			userObj.putInt("guideStep", userProfile.getUserInfo().getGuideStep());
			userObj.putBool("isSetNickname", userProfile.isSetNickname());
			userObj.putInt("vipLv", userProfile.getUserInfo().getVipLv());
			userObj.putSFSObject("resource", userProfile.getResManager().toSFSObject());
			userObj.putSFSObject("buildings", userProfile.getBDManager().toSFSObject());
			userObj.putSFSObject("army", userProfile.getArmyManager().toSFSObject());
			userObj.putSFSObject("science", SFSObject.newInstance()); // userProfile.getScManager().toSFSObject()
			userObj.putSFSObject("devTime", userProfile.getTimeManager().toSFSObject());
			userObj.putSFSArray("inventory", userProfile.getInventory().toSFSArray());
			userObj.putSFSObject("alliance", AllianceService.getAllianceData(userProfile));
			userObj.putBool("cityconst", CityConstructionService.userHasAnyConstruction(userProfile));
			userObj.putSFSObject("payItems", userProfile.getPaymentMgr().getPaylistAsSFSObject());
		}
		ref.putSFSObject("userdata", userObj);
		return ref;
	}

}
